import * as cheerio from 'react-native-cheerio';
import { ISearchResult } from "../def";
import { SupportVideoType, VideoIntroduceInfo, VideoDetailInfo, VideoItem, PlaySource, Episode } from "../icommon/index";

async function search<T extends SupportVideoType>(query: string, page: number, type: T): Promise<ISearchResult<T>> {
    const movies: VideoItem[] = [];
    let url = "https://www.hyst.org/news/1.html";
    switch (type) {
        case "movies":
            url = `https://www.hyst.org/news/1-${page}.html`;
            break;
        case "tv":
            url = `https://www.hyst.org/news/2-${page}.html`;
            break;
        case "cartoon":
            url = `https://www.hyst.org/news/4-${page}.html`;
            break;
        case "all":
            url = `https://www.hyst.org/search.php?searchword=${query}&page=${page}`
            break;
    }
    const res = await fetch(url, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);
    $('.fed-list-item').each((index: number, element: any) => {
        const linkElement = $(element).find('.fed-list-pics');
        const titleElement = $(element).find('.fed-list-title');

        if (linkElement.length > 0 && titleElement.length > 0) {
            const detailUrl = linkElement.attr('href') || '';
            const cover = linkElement.attr('data-original') || '';
            const title = titleElement.text() || '';

            // 从详情地址中提取ID
            const idMatch = detailUrl.match(/\/product\/(\d+)\.html/);
            const id = idMatch ? idMatch[1] : '';

            if (id && title && cover && detailUrl) {
                movies.push({
                    id,
                    title,
                    img: cover,
                    detailUrl
                });
            }
        }
    });

    return {
        data: movies,
        isEnd: movies.length <= 0,
    };
}
async function fetchIntroduceInfo({ id }: { url: string, id: string }): Promise<VideoIntroduceInfo> {
    const target = `https://www.hyst.org/product/${id}.html`;
    const res = await fetch(target, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);

    // 提取基本信息
    const title = $('.fed-deta-content h1').text().trim() || $('title').text().split('_')[0];
    const cover = $('.fed-deta-images .fed-list-pics').attr('data-original') || '';

    // 提取各种字段信息
    const director = $('.fed-deta-content li').filter((i: number, el: any) => {
        return $(el).text().includes('导演：');
    }).text().replace('导演：', '').trim();

    const actor = $('.fed-deta-content li').filter((i: number, el: any) => {
        return $(el).text().includes('主演：');
    }).text().replace('主演：', '').trim();

    const category = $('.fed-deta-content li').filter((i: number, el: any) => {
        return $(el).text().includes('分类：');
    }).text().replace('分类：', '').trim();

    const area = $('.fed-deta-content li').filter((i: number, el: any) => {
        return $(el).text().includes('地区：');
    }).text().replace('地区：', '').trim();

    const year = $('.fed-deta-content li').filter((i: number, el: any) => {
        return $(el).text().includes('年份：');
    }).text().replace('年份：', '').trim();

    const updateTime = $('.fed-deta-content li').filter((i: number, el: any) => {
        return $(el).text().includes('更新：');
    }).text().replace('更新：', '').trim();

    // 提取简介
    const description = $('meta[name="description"]').attr('content');

    // 提取剧情介绍
    const plot = $('.fed-drop-boxs.fed-drop-tops.fed-matp-v').first().text().trim();

    // 提取播放地址
    const playUrl = $('.fed-deta-play').attr('href') || '';
    var playId = '';
    // 从URL中提取ID和集数信息
    const urlMatch = playUrl.match(/\/yxpaly\/(\d+)-(\d+)-(\d+)\.html/);
    if (urlMatch) {
        playId = urlMatch[1];
    }
    return {
        id,
        title,
        img: cover,
        introduce: description ?? plot,
        actor,
        director,
        category,
        area,
        year,
        updateTime,
        detailUrl:playUrl,
    };
};
async function fetchVideoDetailInfo({ id, source, episodeIndex }: {
    url: string
    id: string,
    source?: number,
    episodeIndex?: number
}): Promise<VideoDetailInfo> {
    const  relUrl = `${id}-${source ? source : 0}-${episodeIndex ? episodeIndex : 0}.html`
    const target = `https://www.hyst.org/yxpaly/${relUrl}`;
   
    const res = await fetch(target, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);
    const title = $('title').text().split('_')[0];
    const description = $('meta[name="description"]').attr('content') || '';

    // 提取播放源信息
    const playSources: PlaySource[] = [];
    $('.tabt3 span').each((index: number, element: any) => {
        const sourceId = $(element).attr('id') || '';
        const sourceName = $(element).text().trim();

        if (sourceId && sourceName) {
            playSources.push({
                id: sourceId,
                name: sourceName,
                episodes: []
            });
        }
    });
    // 提取各播放源的选集
    playSources.forEach(source => {
        const episodeList: Episode[] = [];
        $(`.${source.id} .ulNumList li`).each((index: number, element: any) => {
            const episodeElement = $(element).find('a');
            const episodeTitle = episodeElement.attr('title') || '';
            const episodeUrl = episodeElement.attr('href') || '';

            // 从URL中提取ID和集数信息
            const urlMatch = episodeUrl.match(/\/yxpaly\/(\d+)-(\d+)-(\d+)\.html/);
            if (urlMatch && episodeTitle && episodeUrl) {
                episodeList.push({
                    id: urlMatch[1],
                    sourceIndex: parseInt(urlMatch[2], 10),
                    episodeIndex: parseInt(urlMatch[3], 10),
                    title: episodeTitle,
                    url: episodeUrl
                });
            }
        });

        source.episodes = episodeList;
    });

    // 获取当前播放的视频信息
    const scriptText = html;
    const videoInfo: any = {};

    // 提取视频ID
    const vidMatch = scriptText.match(/var vid="(\d+)"/);
    if (vidMatch) {
        videoInfo.id = vidMatch[1];
    }

    // 提取当前播放源
    const pnMatch = scriptText.match(/var pn="([^"]+)"/);
    if (pnMatch) {
        videoInfo.currentSource = pnMatch[1];
    }

    // 提取当前集数
    const vpartMatch = scriptText.match(/var vpart="([^"]+)"/);
    if (vpartMatch) {
        videoInfo.currentEpisode = vpartMatch[1];
    }

    // 提取视频播放地址
    const nowMatch = scriptText.match(/var now="([^"]+)"/);
    if (nowMatch) {
        videoInfo.videoUrl = nowMatch[1];
    }
    return {
        id,
        title,
        img: '',
        introduce: description,
        playSources,
        currentVideoInfo: videoInfo,
        detailUrl:`/yxpaly/${relUrl}`,
    };
};

module.exports = {
    label: "英雄影视",
    appVersion: "1.0.0",
    platform: "hero",
    srcUrl: "https://www.hyst.org/news/1.html",
    author: "petter.he",
    description: "hero",
    enabledSearch: false,
    search,
    fetchIntroduceInfo,
    fetchVideoDetailInfo,

}